import axios, { AxiosInstance, InternalAxiosRequestConfig, AxiosRequestConfig, AxiosError, AxiosResponse } from "axios";

const getToken = () => {
  return localStorage.getItem("userToken");
};
const service: AxiosInstance = axios.create({
  // baseURL: process.env.REACT_APP_BASE_API,
  timeout: 30000,
});

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if (getToken()) config.headers["X-AIS-TOKEN"] = getToken();
    return config;
  },
  (error: AxiosError) => {
    console.log(error);
    return Promise.reject();
  }
);

service.interceptors.response.use(
  (response: AxiosResponse): AxiosResponse["data"] => {
    if (response.status === 200) {
      const res = response.data;
      if (res.ret === -4000) {
        // 重定向跳转
        localStorage.removeItem("userToken");
        localStorage.removeItem("userType");
        localStorage.removeItem("businessType");
        localStorage.removeItem("chainShopId");
        window.location.href = "/";
      } else if (res.ret === -805) { //没有权限
        window.location.replace(window.location.origin + "/noAccess");
      }
      return response;
    } else {
      Promise.reject();
    }
  },
  (error: AxiosError) => {
    console.log(error);
    return Promise.reject();
  }
);

interface RequestParams<T> {
  url: string;
  data?: T;
}

// 定义一个范型函数，用于发送 GET 请求
export function get<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
  return service.get<T>(url, config);
}

// 定义一个范型函数，用于发送 POST 请求
export function post<T>(params: RequestParams<T>, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
  return service.post<T>(params.url, params.data, config);
}

export default service;

// service({

// })
